package com.beerbook;

import java.io.File;
import java.io.FilenameFilter;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

public class EditBeer extends ListActivity implements OnClickListener {

	public static String picturePrefix = "beerbook_";
	
	protected EditText nameText;
	protected EditText breweryText;
	protected EditText categoryText;
	protected EditText styleText;
	protected EditText abvText;
	protected EditText ibuText;
	protected EditText dateText;
	protected EditText ratingText;
	protected EditText notesText;
	protected String pictureText;
    protected Cursor cursor;
    
    private String[] mFiles =  null;
    private Uri[] mUrls;
    private Cursor categoryCursor;
    private int categoryinit;
    private boolean initial=true;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_beer);
    	Button save_button = (Button)findViewById(R.id.Save);
		save_button.setOnClickListener(this);
		Button cancel_button = (Button)findViewById(R.id.Cancel);
		cancel_button.setOnClickListener(this);
		Button picture_button = (Button)findViewById(R.id.beerPicture);
	    picture_button.setOnClickListener(this);
        
        showEditBeer();
        initial=false;
    }
    
    public void showEditBeer(){
        nameText = (EditText) findViewById(R.id.name);
        breweryText = (EditText) findViewById(R.id.brewery);     
        styleText = (EditText) findViewById(R.id.style);
        abvText = (EditText) findViewById(R.id.abv);
        ibuText = (EditText) findViewById(R.id.ibu);       
        dateText = (EditText) findViewById(R.id.date);
        ratingText = (EditText) findViewById(R.id.rating);
        notesText = (EditText) findViewById(R.id.notes);
        
	    //Set Spinner/Cursor
        SQLiteDatabase db = (new BeerDB(this)).getWritableDatabase();
		Cursor c = db.rawQuery("SELECT _id, category FROM category",null);
		String[] from = new String[]{"category"};
		int[] to = new int[]{android.R.id.text1};
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
		adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
		Spinner s = (Spinner) findViewById(R.id.category);
		s.setAdapter(adapter);
		s.setOnItemSelectedListener(new MyOnItemSelectedListener());
        
		//Set Initial Values
	    setInitialValues(getIntent().getIntExtra("beerId", 0));
	    
	    if(categoryCursor != null){
			s.setSelection(categoryCursor.getPosition());
		} else {
			s.setSelection(categoryinit);
		}
	    
	    //Load Image
        String state = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
	        File images = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"/beerbook");
	        File[] imagelist = images.listFiles(new FilenameFilter(){
	        	public boolean accept(File dir, String name){
	        		if(pictureText != null){
	        			return ((name.contains(pictureText)));
	        		}
	        		return false;
	        	}
	        });
	        if(imagelist != null){
		        mFiles = new String[imagelist.length];
		        
		        for(int i = 0; i<imagelist.length;i++){
		        	mFiles[i]=imagelist[i].getAbsolutePath();
		        }
		        mUrls = new Uri[mFiles.length];
		        
		        for(int i=0;i<mFiles.length;i++){
		        	mUrls[i]=Uri.parse(mFiles[i]);
		        }
		        
		        Gallery g = (Gallery)findViewById(R.id.beerGallery);
		        g.setAdapter(new ImageAdapter(this));
		        g.setFadingEdgeLength(40);
	        }
        }
        
		db.close();
    }

    private void setInitialValues(int id) {
    	if(initial){
	    	SQLiteDatabase db = (new BeerDB(this)).getWritableDatabase();
	    	Beer beer = new Beer(db,id);
	    	nameText.setText(beer.getName());
	    	breweryText.setText(beer.getBrewery());
	    	categoryinit = beer.getCategoryId()-1;
	    	styleText.setText(beer.getStyle());
	    	abvText.setText(Double.toString(beer.getAbv()));
	    	ibuText.setText(Double.toString(beer.getIbu()));
	    	dateText.setText(beer.getDate());
	    	ratingText.setText(Double.toString(beer.getRating()));
	    	notesText.setText(beer.getNotes());
	    	pictureText = beer.getPicture();
			db.close();
    	}
	}

	public void savebeer(){
    	SQLiteDatabase db = (new BeerDB(this)).getWritableDatabase();
    	ContentValues cv=new ContentValues();
    	
        cv.put("name",nameText.getText().toString());
        cv.put("brewery",breweryText.getText().toString());
        
        Cursor c = db.query("category", new String[] {"_id","category"}, "category == '"+categoryCursor.getString(categoryCursor.getColumnIndex("category"))+"'",null,null,null,null);
        c.moveToFirst();
        cv.put("category", c.getInt(c.getColumnIndex("_id")));
        
        cv.put("style",styleText.getText().toString());
        
        if(abvText.getText().toString().length() > 0)
        	cv.put("abv",Double.valueOf(abvText.getText().toString()));
        
        if(ibuText.getText().toString().length() > 0)
        	cv.put("ibu",Double.valueOf(ibuText.getText().toString()));
        
        if(dateText.getText().toString().length() > 0)
        	cv.put("date",dateText.getText().toString());
        
        if(ratingText.getText().toString().length() > 0)
        	cv.put("rating",Double.valueOf(ratingText.getText().toString()));
        
        if(notesText.getText().toString() != null)
        	cv.put("notes",notesText.getText().toString());
        
        cv.put("picture",pictureText);

        db.update("beer", cv, "_id = " + getIntent().getIntExtra("beerId", 0),null);	
        db.close();
    }
      
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.Save:
				savebeer();
				finish();
				break;
			case R.id.Cancel:
				finish();
				break;
			case R.id.beerPicture:
				beerPicture();
				break;
		}
	}
	
	public void beerPicture(){
		pictureText = picturePrefix + String.valueOf(System.currentTimeMillis()) + ".jpg";
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
		File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"/beerbook"), pictureText); 
		 
		Uri outputFileUri = Uri.fromFile(file); 
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); 
		 
		startActivityForResult(intent, 1);
	}
	
	@Override 
	protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
		if (requestCode == 1) { 
			switch( resultCode ) { 
		  		case 0: 
		  			break; 
		  		case -1:
		  			showEditBeer(); 
		  		break; 
			} 
		} 
	}
	
	public class MyOnItemSelectedListener implements OnItemSelectedListener {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        	categoryCursor = (Cursor) parent.getItemAtPosition(pos);
        }
        public void onNothingSelected(AdapterView<?> parent) {
        }
    }
	
    public class ImageAdapter extends BaseAdapter {
    	int mGalleryItemBackground;
    	public ImageAdapter(Context c){
    		mContext = c;
    	}
    	public int getCount(){
    		return mUrls.length;
    	}
    	public Object getItem(int position){
    		return position;
    	}
    	public long getItemId(int position){
    		return position;
    	}
    	public View getView(int position, View convertView, ViewGroup partent){
    		ImageView i = new ImageView(mContext);
    		
    		i.setImageURI(mUrls[position]);
    		i.setScaleType(ImageView.ScaleType.FIT_CENTER);
    		i.setLayoutParams(new Gallery.LayoutParams(260,210));
    		return i;
    	}
    	private Context mContext;
    }
	
}